package org.example.consumer.service;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.dto.Stu;
import org.example.util.Constant;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 消费者服务
 *
 * @since 2022/7/12
 **/
@Service
@Slf4j
public class NewConsumeService {

    public static final int count = 500;


    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Resource
    private RedissonClient redisson;

    public Runnable getRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                final Lock lock = new ReentrantLock();
                try {
                    while (true) {
                        List<Stu> student = new LinkedList<>();
                        for (int i = 0; i < RandomUtil.randomInt(count - 100, count + 100); i++) {
                            Stu stu = Stu.builder()
                                    .name(RandomUtil.randomString(10))
                                    .age(RandomUtil.randomInt(0, 100))
                                    .build();
                            student.add(stu);
                        }
                        try {
                            lock.lock();
                            //获取数据到redis
                            RList<Stu> data = redisson.getList(Constant.newKey);
                            data.addAll(student);
                            if (data.size() >= count) {
                                RList<Stu> temp = data.subList(0, count);
                                temp.clear();
                            } else {
                                // log.error("不够" + count + "，size为" + data.size());
                            }
                        } catch (Exception e) {
                            log.error("cC", e);
                        } finally {
                            lock.unlock();
                        }
                    }
                } catch (Exception e) {
                    log.error("异常", e);
                }
            }
        };
    }

    public void run() {
        for (int i = 0; i < 8; i++) {
            executorService.submit(getRunnable());
        }
    }

}
